package com.fzshang.shopping.commen.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fzshang.shopping.commen.bean.Classification;
import com.fzshang.shopping.commen.bean.User;
import com.fzshang.shopping.commen.bean.layuiBean.ResultPage;
import com.fzshang.shopping.commen.bean.layuiBean.VoPage;
import com.fzshang.shopping.commen.mapper.UserMapper;
import com.fzshang.shopping.commen.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzshang.shopping.commen.util.Identification;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 微信信息 服务实现类
 * </p>
 *
 * @author 冯政尚
 * @since 2020-03-03
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public User login(WxMpUser wxMpUser) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("openid", wxMpUser.getOpenId());
        User user = this.getOne(queryWrapper);
        //第一次而登陆  保存
        if (user == null) {
            user = new User();
            user.setCity(wxMpUser.getCity());
            user.setCountry(wxMpUser.getCountry());
            user.setProvince(wxMpUser.getProvince());
            user.setSex(wxMpUser.getSexDesc());
            user.setImge(wxMpUser.getHeadImgUrl());
            user.setNickName(wxMpUser.getNickname().getBytes());
            user.setOpenid(wxMpUser.getOpenId());
            user.setMoeny("0");
            user.setUserIdentity(1);
            user.setIntegral("0");
            user.setCreateTime(System.currentTimeMillis());
            user.setDiscountCode(Identification.getStringRandom(8));
            this.save(user);
            //否则 更新性别 城市 头像
        } else {
            user.setCity(wxMpUser.getCity());
            user.setCountry(wxMpUser.getCountry());
            user.setProvince(wxMpUser.getProvince());
            user.setSex(wxMpUser.getSexDesc());
            user.setImge(wxMpUser.getHeadImgUrl());
            user.setNickName(wxMpUser.getNickname().getBytes());
            this.updateById(user);
        }
        return user;
    }



    /**
     * @param voPage
     * @return 后台查询
     */
    @Override
    public ResultPage<User> selectMyPage(VoPage voPage ) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("page", (voPage.getPage() - 1) * voPage.getLimit());
        paramMap.put("limit", voPage.getLimit());
        List<User> list = baseMapper.selectMyPage(paramMap);
        Integer count = baseMapper.countMyPage(paramMap);
        ResultPage<User> resultPage = new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }

}
